from typing import List
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from app.config.database_config import PgManager
from app.services.passenger_service import PassengerService
from app.schemas.passenger import PassengerCreate, PassengerUpdate, PassengerResponse

router = APIRouter(prefix="/passengers", tags=["passengers"])

def get_passenger_service(db: Session = Depends(PgManager.get_db_static)) -> PassengerService:
    return PassengerService(db)

@router.post("/", response_model=PassengerResponse)
def create_passenger(
    passenger: PassengerCreate,
    service: PassengerService = Depends(get_passenger_service)
):
    """创建新乘客"""
    # 检查邮箱是否已存在
    existing_passenger = service.get_passenger_by_email(passenger.email)
    if existing_passenger:
        raise HTTPException(status_code=400, detail="邮箱已被注册")
    
    # 检查护照号是否已存在
    if passenger.passport_number:
        existing_passenger = service.get_passenger_by_passport(passenger.passport_number)
        if existing_passenger:
            raise HTTPException(status_code=400, detail="护照号已存在")
    
    return service.create_passenger(passenger)

@router.get("/{passenger_id}", response_model=PassengerResponse)
def get_passenger(
    passenger_id: int,
    service: PassengerService = Depends(get_passenger_service)
):
    """根据ID获取乘客信息"""
    passenger = service.get_passenger(passenger_id)
    if not passenger:
        raise HTTPException(status_code=404, detail="乘客未找到")
    return passenger

@router.get("/email/{email}", response_model=PassengerResponse)
def get_passenger_by_email(
    email: str,
    service: PassengerService = Depends(get_passenger_service)
):
    """根据邮箱获取乘客信息"""
    passenger = service.get_passenger_by_email(email)
    if not passenger:
        raise HTTPException(status_code=404, detail="乘客未找到")
    return passenger

@router.get("/passport/{passport_number}", response_model=PassengerResponse)
def get_passenger_by_passport(
    passport_number: str,
    service: PassengerService = Depends(get_passenger_service)
):
    """根据护照号获取乘客信息"""
    passenger = service.get_passenger_by_passport(passport_number)
    if not passenger:
        raise HTTPException(status_code=404, detail="乘客未找到")
    return passenger

@router.get("/", response_model=List[PassengerResponse])
def get_passengers(
    skip: int = Query(0, ge=0, description="跳过的记录数"),
    limit: int = Query(100, ge=1, le=100, description="返回的记录数"),
    service: PassengerService = Depends(get_passenger_service)
):
    """获取乘客列表"""
    return service.get_passengers(skip=skip, limit=limit)

@router.get("/search/", response_model=List[PassengerResponse])
def search_passengers(
    q: str = Query(..., min_length=1, description="搜索关键词"),
    service: PassengerService = Depends(get_passenger_service)
):
    """搜索乘客（支持姓名、邮箱、护照号、手机号模糊搜索）"""
    return service.search_passengers(q)

@router.put("/{passenger_id}", response_model=PassengerResponse)
def update_passenger(
    passenger_id: int,
    passenger_update: PassengerUpdate,
    service: PassengerService = Depends(get_passenger_service)
):
    """更新乘客信息"""
    passenger = service.update_passenger(passenger_id, passenger_update)
    if not passenger:
        raise HTTPException(status_code=404, detail="乘客未找到")
    return passenger

@router.delete("/{passenger_id}")
def delete_passenger(
    passenger_id: int,
    service: PassengerService = Depends(get_passenger_service)
):
    """删除乘客"""
    success = service.delete_passenger(passenger_id)
    if not success:
        raise HTTPException(status_code=404, detail="乘客未找到")
    return {"message": "乘客删除成功"}